<?php

/**
 * 安卓推送服务
 * 
 */
class AndroidPN
{
    /**
     * 开发模式
     *
     * @var int
     */
    const MODE_DEV = 0;

    /**
     * 生产模式
     * @var int
     */
    const MODE_PRODUCT = 1;

    protected $_config = array
    (
        self::MODE_DEV => array( 'host' => 'http://127.0.0.1' , 'port' => 7070 ) ,
        self::MODE_PRODUCT => array( 'host' => 'http://127.0.0.1' , 'port' => 7070 ) ,
    );
    
    /**
     * 当前模式
     *
     * @var int
     */
    protected $_currentMode = self::MODE_DEV;

    /**
    * 单例对象
    */
    public static $singletonObject = null;

    /**
    * 获取单例
    * @param $uId 用户ID
    * @return Apns
    */
    public static function getInstance()
    {
        if( self::$singletonObject == null )
        {
            self::$singletonObject = new self();
        }

        return self::$singletonObject;
    }

    protected function __construct()
    {
        $apnsConfig = & Common::getConfig( 'ApnsConfig' );
        $this->_currentMode = $apnsConfig['mode'];
        $this->_cert = $apnsConfig['cert'];
    }
    
    /**
     * 向指定设备推送信息
     *
     * @param string $deviceToken //64位字符串
     * @param string $alert //通知内容
     * @param int $badge //通知数字
     * @param string $sound //通知声音
     */
    public function send( $deviceToken ,  $payload )
    {
        $post_data = array();
        $post_data['broadcast'] = 'N';
        $post_data['username'] = $deviceToken;
        $post_data['title'] = $payload['title'];
        $post_data['message'] = $payload['message'];
        $post_data['uri'] = $payload['uri'];
        $url = $this->_config[$this->_currentMode]['host'].':'.$this->_config[$this->_currentMode]['port'].'/notification.do?action=send';
        $o = "";
        foreach ($post_data as $k=>$v)
        {
            $o.= "$k=".urlencode($v)."&";
        }
        $post_data=substr($o,0,-1);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_URL,$url);

        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        $result = curl_exec($ch);
    }
}
?>
